"use client";

import { useState } from "react";
import { CheckIcon, CopyIcon } from "lucide-react";

interface CopyButtonProps {
  text: string;
}

export function CopyButton({ text }: CopyButtonProps) {
  const [isCopied, setIsCopied] = useState(false);

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setIsCopied(true);
      setTimeout(() => setIsCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy text:", err);
    }
  };

  return (
    <button
      onClick={copy}
      className="absolute right-3 top-3 p-2 rounded-lg bg-white/10 hover:bg-white/20 transition-colors opacity-0 group-hover:opacity-100"
      title="复制代码"
    >
      {isCopied ? (
        <CheckIcon className="size-4 text-emerald-400" />
      ) : (
        <CopyIcon className="size-4 text-white/60" />
      )}
    </button>
  );
}